//获取应用实例  
var t = getApp(),
    a = t.requirejs("core");
var loading = false;

Page({
  data: {
      list: [],
      post_message: '',
      post_type: 1,
      pic_show: false,
      pic_path: '',
      status: true,
      show_news: false,
      state: 0, //1:发送中；2：失败
      send_ok: true
  },
  
  /**
   * 图片预览
   */
  previewImage: function (e) {
    var that = this,
      url = a.pdata(e).url;
    wx.previewImage({
      current: url, // 当前显示图片的http链接
      urls: [url]// 需要预览的图片http链接列表
    })
  },

  onLoad: function (e) {
      console.log("option",e)
      var that = this;

      if (e && e.id) {
          t.globalData.card_id = e.id;
      }

      // 获取名片信息
      that.getInfo();

      var interval = setInterval(function () {
          if (!that.data.status) {
              clearInterval(interval);
          }

          // 定时获取信息
          that.getnews();
      }.bind(this), 1000);
  },

  chooseImageTap1: function (e) {
    var id = a.pdata(e).id;
    this.upload(this, id, 'chat_pic');
  },
  onHide: function () {

  },
  onUnload:function(){
    console.log(3344)
    this.setData({
      status:false
    })
  },

  // 定时获取消息
  getnews:function(){
      var that = this;
      var list = that.data.list;

    wx.request({
      url: t.siteInfo.siteroot + '?i=' + t.siteInfo.uniacid + '&t=undefined&v=1.0.0&from=wxapp&c=entry&a=wxapp&do=Card_timelynews&staff_id=' + t.globalData.card_id + '&user_id=' + t.getCache('userinfo').uid+'&m=yb_mingpian&sign=1d917db727d0aa4e23ca117826fa3153', //仅为示例，并非真实的接口地址
      data: {},
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function (t) {
        console.log("news",t)
        if (t.errMsg == "request:ok") {
          if (typeof (t.data) == "string") {
            if (t.data.indexOf("html") >= 0 && t.data.indexOf("head") >= 0 && t.data.indexOf("body") >= 0) { return; }
          }
          if (t.data == '') {
            return;
          }
          if (typeof t.data == 'string') {
            t.data = a.json_parse(t.data);
          }
          if (t.data.code == 0) {
           // if (list.length != t.data.info.length) {
            if (that.data.send_ok) {
              that.setData({
                post_type: 1,
                pic_path: '',
                post_message: '',
                pic_show: false,
                show_news:false,
                state:0,
                send_ok:false
              })
              that.pageScrollToBottom(t.data.info.length*100);//滑到地步
            }
            that.setData({
              list: t.data.info
            })
          }
        }
      }
      })
  },

  //发送消息
  bindconfirm:function(k){
    var e = {};
      e.formid = '';
    if (k && k.detail && k.detail.formId) {
      
      e.formid = k.detail.formId;
      e.openid = getApp().getCache("userinfo").openid;
      e.username = getApp().getCache("userinfo").nickName;
      a.get('Market/getFormid', e, function (t) {
        console.log(t)
      })
    }
    if(loading){
      return;
    }
    
    var that=this,
    post_type=that.data.post_type;
    that.setData({
      //show_news:true,
      state:1
    })
    
    if (post_type == 1) {
      var post_message = that.data.post_message;
      post_message = post_message.replace(/\s*/g, "");
      if (!post_message) {
        a.warning('内容不能为空');
        return;
      }
    }else{
      if(that.data.pic_path==''){
        a.warning('发送图片失败');
        return;
      }
      var  post_message = that.data.pic_path;
    }
    
    loading=true;
    //a.loading('发送中...');
    a.post('Card/addnews',{
      staff_id: t.globalData.card_id,
      user_id: t.getCache('userinfo').uid,
      post_message: post_message,
      post_type: post_type
    },function(t){
      if(t.code==0){
        //推送
        a.get('Wxpush/addnewsPush', {
          formid: e.formid,
          user_id: t.user_id,
          staff_id: t.staff_id,
          message_id:t.info,
        }, function (tt) {

          console.log("push",tt)
          // console.log(22222222);
        })
      }
      a.hideLoading();
      loading = false;
      that.setData({
        send_ok:true,
        post_message: '',
      })
      // that.setData({
      //   post_type:'',
      //   pic_path:'',
      //   post_message:'',
      //   pic_show: false
      // })
      if(t.code==1){
          that.setData({
            state:2
          })
        //a.error(t.msg);
      }
    })
  },

  // 获取名片信息
  getInfo: function () {
      var that = this;
      a.get('Card/CardInfo', { id: t.globalData.card_id, }, function (t) {
          if (t.code == 0) {
              a.ReName(t.info.user_name ? t.info.user_name : '聊天');
              that.setData({
                show: true,
                info: t.info
              })
          } else {
              a.alert(t.msg);
          }
      });
  },

  show_pic_button:function(){
  var i=this.data.pic_show;
  this.setData({
    pic_show: i?false:true
  })
  },
  pageScrollToBottom: function (aa) {
    console.log('滚动到底部')
    wx.createSelectorQuery().select('#bd').boundingClientRect(function (rect) {
      // 使页面滚动到底部
      wx.pageScrollTo({
        scrollTop: aa//rect.bottom
      })
    }).exec()
  },

  Clipboard: function (e) {
    var i = a.pdata(e);
    t.userlog(3, '微信', 'chat_copy');
    a.Clipboard(i.i);
  },
  phone: function (e) {
    t.userlog(5, '电话', 'chat_call');
    a.phone(e);
  },
 
  
  url: function (e) {
    var id = a.pdata(e).i;
    if (id == 1) {
      // 名片详情页
      a.jump('/yb_mingpian/pages/cardinfo/index', 4);
    } else if(id==2) {
      // 官网页面
      a.jump('/yb_mingpian/pages/index/index', 4)
    } else if (id == 3) {
      // 商城页面
      a.jump('/yb_mingpian/pages/shop/index', 4)
    } else if (id == 4) {
      // 动态页面
      a.jump('/yb_mingpian/pages/message/index', 4)
    }
  },

  /**
  * 图片上传
  * this
  * n文件夹名称
  */
  upload: function (that, field, n) {
    var _this = this;
    wx.showActionSheet({
      itemList: ['从相册中选择', '拍照'],
      itemColor: "#f7982a",
      success: function (res) {
        if (!res.cancel) {
          if (res.tapIndex == 0) {
            _this.chooseWxImage('album', that, field, n)
          } else if (res.tapIndex == 1) {
            _this.chooseWxImage('camera', that, field, n)
          }
          
        }
      }
    })
  },
  chooseWxImage: function (type_, that, field, n) {
    var _this = this,
      site = getApp().siteInfo,
      url = site.siteroot + '?i=' + site.uniacid + '&t=undefined&v=' + site.version + '&from=wxapp&c=entry&a=wxapp&do=index_uploadFile&path=' + n + '&m=yb_mingpian&sign=5201314';
    wx.chooseImage({
      sizeType: ['original', 'compressed'],
      sourceType: [type_],
      success: function (res) {
          wx.uploadFile({
            url: url,
            filePath: res.tempFilePaths[0],
            name: 'file_upload',
            success: function (res) {

              if (res.data != null && res.data != '') {
                console.log(res.data)
                that.setData({
                  pic_path: res.data,
                  post_type:2
                })
                that.bindconfirm();
              } else {
                a.error('上传失败，请重试')
              }
            }
          })
        
      }
    })
  },
  bindblur:function(e){
    console.log(e)
    this.setData({
      post_message:e.detail.value
    })
  }

})  